<template>
  <div class="pagination">
    <!-- 分页器上部分 -->
    <button :disabled="pageNo==1" @click="pageInfo(pageNo-1)">上一页</button>
    <button v-if="startNumAndEndNum.start>1" @click="pageInfo(1)" :class="{active:pageNo==1}">1</button>
    <span v-if="startNumAndEndNum.start >2">···</span>

    <!-- 中间连续页部分 -->
    <button
      v-for="(page, index) in (startNumAndEndNum.end)"
      v-if="page>=startNumAndEndNum.start"
      :key="index"
      @click="pageInfo(page)"
      :class="{active:pageNo==page}"
    >{{page}}</button>

    <!-- 分页器下部分 -->
    <span v-if="startNumAndEndNum.end < totalPage-1">···</span>
    <button
      v-if="startNumAndEndNum.end < totalPage"
      @click="pageInfo(totalPage)"
      :class="{active:pageNo==totalPage}"
    >{{totalPage}}</button>
    <button :disabled="pageNo==totalPage" @click="pageInfo(pageNo+1)">下一页</button>
    <button style="margin-left: 1.875rem">共 {{total}} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  // 接收父亲传递来的参数
  props: ['pageNo', 'pageSize', 'total', 'continues'],
  computed: {
    // 总页数
    totalPage () {
      // 向上取整
      return Math.ceil(this.total / this.pageSize);
    },
    // 计算连续页码的起始数字和结束数字
    startNumAndEndNum () {
      // 把vc实例的props属性解构到变量中
      const { pageNo, totalPage, continues } = this;
      // 初始化连续页的起始页码和结束页码
      let start = 0;
      let end = 0;
      // 判断总页数够不够连续页码数多
      if (totalPage < continues) {
        start = 1;
        end = totalPage;
      } else {
        // 起始页码 = 当前页码 - 连续分页数/2（取整）
        start = pageNo - parseInt(continues / 2);
        // 结束页码 = 当前页码 + 连续分页数/2（取整）
        end = pageNo + parseInt(continues / 2);
        // 把分页器中不正常的数字纠正（start<1 &&end > pageNo）
        if (start < 1) {
          start = 1;
          end = continues;
        }
        if (end > totalPage) {
          end = totalPage,
            start = totalPage - continues + 1
        }
      }
      return { start, end }
    }
  },
  methods: {
    // 给父组件传递分页器信息
    pageInfo (pageNo) {
      this.$bus.$emit('getPageNo', pageNo)
    }
  }
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;

  button {
    margin: 0 0.3125rem;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 0.125rem;
    padding: 0 0.3125rem;
    vertical-align: top;
    display: inline-block;
    font-size: 0.8125rem;
    min-width: 2.21875rem;
    height: 1.875rem;
    line-height: 1.75rem;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }

  span {
    display: inline-block;
    width: 2.21875rem;
    height: 1.875rem;
    line-height: 2.1875rem;
  }
}
.active {
  background-color: skyblue;
}
</style>

